package com.study.controller;

import com.study.annotation.NotControllerResponseAdvice;
import com.study.enums.ResultCodeEnum;
import com.study.pojo.common.Result;
import com.study.pojo.dto.Heartbeat;
import com.study.service.HeartbeatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/heart")
public class HeartbeatController {
    @Autowired
    private HeartbeatService heartbeatService;

    /**
     * 倒序查询我给对象添加的所有事件 并指定从哪里开始查询多少条数
     *
     * @param start 开始位置 (start - 1) * num
     * @param num   条数
     */
    @RequestMapping("/query/all/{loveId}/{start}/{num}")
    public Result<?> queryAllHeart(@PathVariable("loveId") Integer loveId, @PathVariable("start") Integer start, @PathVariable("num") Integer num) {
        Map<String, Object> msg = new HashMap<>();
        try {
            List<Heartbeat> heartbeats = heartbeatService.queryAll(loveId, (start - 1) * num, num);
            int count = heartbeatService.getCount(loveId);
            Heartbeat lastHeartbeat = heartbeatService.getLastHeartbeat(loveId);
            msg.put("total", count);
            msg.put("page", ((start - 1) * num) / num + 1);
            msg.put("heart", lastHeartbeat.getTotalPoints());
            msg.put("list", heartbeats);
            return Result.success(ResultCodeEnum.QUERY_SUCCESS, msg);
        } catch (Exception e) {
            return Result.failed(ResultCodeEnum.QUERY_FAILURE);
        }
    }

    @PostMapping("/insert")
    public Result<?> insertHeart(@RequestBody Heartbeat heartbeat) {
        System.out.println("save => " + heartbeat);
        heartbeatService.insertHeart(heartbeat);

        return Result.success(ResultCodeEnum.SAVE_SUCCESS);
    }

    /**
     * @param id 对象id love_id
     * @return 我给对象最后一次添加的数据
     */
    @GetMapping("/query/{id}")
    private Heartbeat getLastHeartbeat(@PathVariable("id") Integer id) {

        return heartbeatService.getLastHeartbeat(id);
    }

    // 根据id查询心跳事件
    @GetMapping("/find/{id}")
    public Heartbeat getHeartbeatById(@PathVariable("id") Integer id) {

        return heartbeatService.getHeartbeatById(id);
    }

    @PostMapping("/update")
    @NotControllerResponseAdvice
    public String updateHeart(@RequestBody Heartbeat heartbeat) {
        heartbeatService.updateHeartbeat(heartbeat);

        return "更新成功";
    }

}
